import MarkdownIt from "markdown-it";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";

import copyImage from "@img/dialog/copy.png";

// 创建markdown实例
const md: any = new MarkdownIt({
  html: true,
  highlight: function (str: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return (
          '<pre class="hljs" style="position:relative;background-color:#000;color: #fff;padding:20px">' +
          '<code style="color: #fff;background-color: transparent">' +
          hljs.highlight(lang, str, true).value +
          "</code>" +
          '<span class="copy-btn" onclick="copyCode(this)">' +
          `<img src="${copyImage}" alt="copy" />` +
          "</span>" +
          "</pre>"
        );
      } catch (__) {}
    }

    return (
      '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
    );
  },
});

window.copyCode = function (button: any) {
  const copyEl = button.previousElementSibling;
  const textArea = document.createElement("textarea");
  textArea.value = copyEl.innerText;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("copy");
  document.body.removeChild(textArea);
};

export default md;
